﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rung.Common
{
    /// <summary>
    /// 性能测试辅助类。
    /// </summary>
    public static class PerformanceCounter
    {
        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
        private static long lStart;
        private static long lEnd;
        private static long ticks;

        static PerformanceCounter()
        {
            lStart = 0L;
            lEnd = 0L;
            IsRunning = false;
        }

        private static bool IsRunning;

        public static TimeSpan Elapsed
        {
            get
            {
                return TimeSpan.FromTicks(ElapsedTicks);
            }
        }

        public static long ElapsedTicks
        {
            get 
            {
                if (IsRunning)
                    Stop();

                return lEnd - lStart;
            }
        }

        public static string ElapsedChineseTime
        {
            get
            {
                TimeSpan span = TimeSpan.FromTicks(ElapsedTicks);

                string result;
                int ms = span.Milliseconds;
                int s = span.Seconds;
                result = string.Format("{0}.{1}秒", s, ms);
                int m = span.Minutes;
                if (m > 0) result = string.Format("{0}分{1}", m, result);
                int h = span.Hours;
                if (h > 0) result = string.Format("{0}时{1}", h, result);
                int d = span.Days;
                if (d > 0) result = string.Format("{0}天{1}", d, result);

                return result;
            }
        }

        /// <summary>
        /// 启动记时。
        /// </summary>
        public static void Start()
        {
            QueryPerformanceCounter(out lStart);
            IsRunning = true;
        }

        /// <summary>
        /// 重新开始一个新的记时。
        /// </summary>
        public static void Restart()
        {
            Reset();
            Start();
        }

        /// <summary>
        /// 结束记时。
        /// 此时可以通过 ElapsedTicks 和 Elapsed 查看时长。
        /// </summary>
        public static void Stop()
        {
            QueryPerformanceCounter(out lEnd);
            ticks = lEnd - lStart;
            IsRunning = false;
        }

        public static void Reset()
        {
            lStart = 0L;
            lEnd = 0L;
            ticks = 0L;
            IsRunning = false;
        }
    }
}
